import { GameId } from '/@/api/general/model/cardModel';
import type { SeriesList, SeriesItem } from '/@/api/general/model/seriesModel';
import { reactive, toRaw } from 'vue';
import { awaitWrap } from '/@/utils';
import { uniqBy, filter } from 'lodash-es';
import { SeriesListApi } from '/@/api/general/series';

export function useSeriesOptions() {
  type YearSeries = {
    year: number;
    count: number;
    list: SeriesList;
  };
  const seriesData = reactive<SeriesList>([]);
  const yearSeriesData = reactive<YearSeries[]>([]);

  const seriesGetData = async (params: GameId) => {
    const [error, result] = await awaitWrap(SeriesListApi({ game_id: params.game_id }));
    if (error || !result) {
      return;
    }
    for (const item of result) {
      item.checked = false;
      seriesData.push(item);
    }
    handleSeriesDate(toRaw(seriesData));
  };

  const handleSeriesDate = (data: SeriesList) => {
    const countObj: { [p: string]: number } = {};
    yearSeriesData.map((item) => {
      countObj[item.year] = item.count;
    });
    yearSeriesData.length = 0;
    const cloneData = toRaw(data);
    const yearArr = uniqBy(cloneData, 'publish_year');
    for (const year of yearArr) {
      const list = filter(cloneData, (item: SeriesItem) => {
        return year.publish_year === item.publish_year;
      });
      let count = countObj[year.publish_year] || 0;
      !count
        ? list.map((item) => {
            item.checked ? (count += 1) : null;
          })
        : null;
      yearSeriesData.push({ year: year.publish_year, list: list, count: count });
    }
    yearSeriesData.sort((a, b) => {
      return b.year - a.year;
    });
  };

  const resetSeriesData = () => {
    seriesData.length = 0;
    yearSeriesData.length = 0;
  };

  return {
    seriesGetData,
    resetSeriesData,
    seriesData,
    yearSeriesData,
    handleSeriesDate,
  };
}
